package com.liustar.common.rpc;


import com.alibaba.fastjson.JSON;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * RPC Result.
 *
 * @author Leo
 * @serial Don't change the class name and properties.
 */
public class RpcResult implements Serializable {

    private static final long serialVersionUID = -6925985956850002586L;

    private Object result;

    private Throwable exception;

    private Map<String, Object> attachments = new HashMap<>();

    private Map pageInfo;

    public RpcResult() {
    }

    public RpcResult(Object result) {
        this.result = result;
    }

    public RpcResult(Throwable exception) {
        this.exception = exception;
    }

    public Object recreate() throws Throwable {
        if (exception != null) {
            throw exception;
        }
        return result;
    }

    public <T> T getValue() {
        return (T) result;
    }

    public <T> void setValue(T value) {
        this.result = value;
    }

    public Throwable getException() {
        return exception;
    }

    public void setException(Throwable e) {
        this.exception = e;
    }

    public boolean hasException() {
        return exception != null;
    }

    public Map<String, Object> getAttachments() {
        return attachments;
    }

    public void setAttachments(Map<String, Object> map) {
        if (map != null && map.size() > 0) {
            attachments.putAll(map);
        }
    }

    public Object getAttachment(String key) {
        return attachments.get(key);
    }

    public Object getAttachment(String key, Object defaultValue) {
        Object result = attachments.get(key);
        if (result == null) {
            result = defaultValue;
        }
        return result;
    }

    public void setAttachment(String key, Object value) {
        attachments.put(key, value);
    }

    public Map getPageInfo() {
        return pageInfo;
    }

    public void setPageInfo(Map pageInfo) {
        this.pageInfo = pageInfo;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}